import React, { useEffect, useRef, useState } from 'react';
import { Button, Dialog } from "@material-tailwind/react";

const VideoRecorder = ({
    completeUpload,
    readNum
}: {
    completeUpload: (url: any) => void,
    readNum: string
}) => {
    const [isRecording, setIsRecording] = useState(false);
    const [videoURL, setVideoURL] = useState('');
    const mediaRecorderRef = useRef(null);
    const videoRef = useRef(null);
    const [countdown, setCountdown] = useState(10); // 初始倒计时10秒
    const countdownTimerRef = useRef(null);

    // 打开摄像头，显示预览
    useEffect(() => {
        const enableStream = async () => {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ video: true });
                videoRef.current.srcObject = stream;
            } catch (err) {
                console.error('Cannot access the camera', err);
            }
        };

        enableStream();

        // 组件卸载时关闭摄像头
        return () => {
            if (videoRef.current && videoRef.current.srcObject) {
                videoRef.current.srcObject.getTracks().forEach(track => track.stop());
            }
        };
    }, []);

    const startRecording = () => {
        if (videoRef.current && videoRef.current.srcObject) {
            mediaRecorderRef.current = new MediaRecorder(videoRef.current.srcObject);
            let chunks = [];
            mediaRecorderRef.current.ondataavailable = event => {
                chunks.push(event.data);
            };

            mediaRecorderRef.current.onstop = () => {
                const blob = new Blob(chunks, { 'type': 'video/mp4' });
                // setVideoURL(URL.createObjectURL(blob));
                console.log('blob',blob)
                completeUpload(blob);
            };

            mediaRecorderRef.current.start();
            setIsRecording(true);

            // 开始倒计时
            setCountdown(10); // 重置倒计时为10秒
            countdownTimerRef.current = setInterval(() => {
                setCountdown(prevCountdown => {
                    if (prevCountdown === 1) {
                        stopRecording(); // 倒计时结束时停止录制
                    }
                    return prevCountdown - 1;
                });
            }, 1000);
        }
    };



    const stopRecording = () => {
        if (mediaRecorderRef.current) {
            mediaRecorderRef.current.stop();
            setIsRecording(false);
            clearInterval(countdownTimerRef.current);
        }
    };

    return (
        <div className='w-full min-h-screen'>
            <video ref={videoRef} className='fixed top-0 right-0 bottom-0 left-0 w-full h-full object-cover' autoPlay muted></video>
            {/* {isRecording ? (
                <button onClick={stopRecording}>停止录制</button>
            ) : (
                <button onClick={startRecording}>开始录制</button>
            )} */}
            {/* {videoURL && (
                <div>
                    <video src={videoURL} style={{ width: '100%' }} controls></video>
                    <a href={videoURL} download="recorded_video.mp4">下载视频</a>
                </div>
            )} */}
            <div className='fixed top-0 right-0 bottom-0 left-0 w-full h-full z-10'>
                <div className='mt-16'>
                    <p className='text-center text-white font-bold'>录像将在 <span className='text-danger text-xl'>{countdown}秒</span> 后结束</p>
                    <div className='bg-secondaryTextColor/45 py-3 '>
                        <p className='text-center text-warning text-sm'>朗读以下数字</p>
                        <p className='text-center text-warning text-3xl font-bold'>{readNum}</p>

                    </div>
                </div>
            </div>
            <div className='fixed bottom-5 left-0 w-full z-10'>
                <div className='px-5'>
                    <Button variant="filled" onClick={() => {
                        if (isRecording) {
                            stopRecording()
                        } else {
                            startRecording();
                        }
                    }} className={`bg-mainColor text-white p-3 text-center  rounded-full w-full text-sm `} placeholder={'undefined'} onPointerEnterCapture={undefined} onPointerLeaveCapture={undefined}>
                        {isRecording ? '停止录制' : '开始录制'}
                    </Button>
                </div>
            </div>
        </div>
    );
};

export default VideoRecorder;
